package com.app.couponsharelife.ui.main.home.search

import android.graphics.drawable.AnimationDrawable
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.LifeShopBean
import com.app.couponsharelife.data.bean.LifeShopRecord
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.bean.SearchHistoryBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.adapter.LifeShopListAdapter
import com.app.couponsharelife.utils.AppUtils
import com.scwang.smartrefresh.layout.api.RefreshFooter
import com.scwang.smartrefresh.layout.api.RefreshHeader
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.constant.RefreshState
import com.scwang.smartrefresh.layout.listener.OnMultiPurposeListener
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_lifesearch_result.*
import kotlinx.android.synthetic.main.base_refresh_head.*
import kotlinx.android.synthetic.main.base_title_search_white.*

/**
 *Created by xct on 2019/1/9
 *Description:本地生活搜索结果页面
 */
class LifeSearchResultActivity:BaseActivity() {
    private var pageIndex=1
    private var longitude=""
    private var latitude=""
    private var keyword=""
    private var shopList= arrayListOf<LifeShopRecord>()
    private var mAdapter:LifeShopListAdapter?=null
    private var historyList= arrayListOf<String>()
    override val viewLayoutId: Int
        get() = R.layout.activity_lifesearch_result

    override fun initViews() {
        AppUtils.initImmersionBar(this,true)
        longitude=AppUtils.getString("Longitude", Contacts.HZ_CENTER_LONGITUDE)
        latitude=AppUtils.getString("Latitude", Contacts.HZ_CENTER_LATITUDE)
        keyword=intent.getStringExtra("KeyWord")
        setRefresh()
        mAdapter=LifeShopListAdapter(this,shopList)
        lifesearch_result_rv.layoutManager=LinearLayoutManager(this)
        lifesearch_result_rv.adapter=mAdapter
        getShopList(false,true)
        basetitle_llclose.setOnClickListener {
            finish()
        }
        basetitle_edit.setText(keyword)
        basetitle_edit.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH){
                keyword=basetitle_edit.text.toString().trim()
                if (keyword.isNotEmpty()){
                    setKey(keyword)
                    pageIndex=1
                    getShopList(false,true)
                }else{
                    showToastMsg("请输入搜索内容！")
                }
                true
            }else{
                false
            }
        }
        basetitle_imag_delete.setOnClickListener {
            basetitle_edit.setText("")
        }
    }
    private fun setKey(keyWord:String){
        if (!historyList.contains(keyWord)){
            if (historyList.size>=10){
                historyList.removeAt(9)
                historyList.add(0,keyWord)
            }else{
                historyList.add(0,keyWord)
            }
        }
        AppUtils.setString("searchHistory", Gson().toJson(SearchHistoryBean(historyList)))
    }
    private fun setRefresh(){
        hotsale_refreshimg.setImageResource(R.drawable.anim_refresh)
        val animationDrawable=hotsale_refreshimg.drawable as AnimationDrawable
        lifesearch_result_smart.setOnMultiPurposeListener(object : OnMultiPurposeListener {
            override fun onFooterMoving(footer: RefreshFooter?, isDragging: Boolean, percent: Float, offset: Int, footerHeight: Int, maxDragHeight: Int) {

            }

            override fun onHeaderStartAnimator(header: RefreshHeader?, headerHeight: Int, maxDragHeight: Int) {

            }

            override fun onFooterReleased(footer: RefreshFooter?, footerHeight: Int, maxDragHeight: Int) {

            }

            override fun onStateChanged(refreshLayout: RefreshLayout, oldState: RefreshState, newState: RefreshState) {

            }

            override fun onHeaderMoving(header: RefreshHeader?, isDragging: Boolean, percent: Float, offset: Int, headerHeight: Int, maxDragHeight: Int) {
                setAnima(percent)
            }

            override fun onFooterFinish(footer: RefreshFooter?, success: Boolean) {

            }

            override fun onFooterStartAnimator(footer: RefreshFooter?, footerHeight: Int, maxDragHeight: Int) {

            }

            override fun onHeaderReleased(header: RefreshHeader?, headerHeight: Int, maxDragHeight: Int) {
                animationDrawable.start()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                getShopList(false,false)
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex=1
                getShopList(true,false)
            }

            override fun onHeaderFinish(header: RefreshHeader?, success: Boolean) {
                hotsale_refreshimg.setImageResource(R.drawable.refresh_0)
                animationDrawable.stop()
            }
        })
    }
    private fun setAnima(vlaue:Float){
        val layoutParams=hotsale_refreshimg.layoutParams as ConstraintLayout.LayoutParams
        layoutParams.matchConstraintPercentHeight=vlaue/2
        layoutParams.dimensionRatio="0.875:1"
        hotsale_refreshimg.layoutParams=layoutParams
    }
    private fun getShopList(isRefresh:Boolean,isFirst:Boolean){
        if (isFirst){
            showProgressDialog("加载中...")
        }
        val map= HashMap<String,String>()
        map["pageNo"]=pageIndex.toString()
        map["pageSize"]="10"
        map["keyword"]=keyword
        map["Longitude"]=longitude
        map["Latitude"]=latitude
        map["distance"]="60"
        RetrofitWorker.retrofitWorker.lifeGetShopPage(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<LifeShopBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<LifeShopBean>) {
                        if (isFirst){
                            dismissProgressDialog()
                        }
                        if (isRefresh){
                            lifesearch_result_smart.finishRefresh()
                        }
                        if (it.code==200){
                            if (it.data!=null&&it.data!!.records!=null&&it.data!!.records!!.isNotEmpty()){
                                if (pageIndex==1){
                                    shopList.clear()
                                }
                                shopList.addAll(it.data!!.records as ArrayList)
                                if (shopList.size>=it.data!!.total!!){
                                    lifesearch_result_smart.finishLoadMoreWithNoMoreData()
                                }else{
                                    if (pageIndex>1){
                                        lifesearch_result_smart.finishLoadMore()
                                    }
                                }
                                pageIndex++
                                mAdapter!!.notifyDataSetChanged()
                            }else{
                                if (pageIndex==1&&shopList.size==0){
                                    lifesearch_result_llerror.visibility=View.VISIBLE
                                    lifesearch_result_rv.visibility=View.GONE
                                }else{
                                    lifesearch_result_llerror.visibility=View.GONE
                                    lifesearch_result_rv.visibility=View.VISIBLE
                                }
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (isFirst){
                            dismissProgressDialog()
                        }
                        if (isRefresh){
                            lifesearch_result_smart.finishRefresh()
                        }
                        if (pageIndex>1){
                            lifesearch_result_smart.finishLoadMore()
                        }
                        if (pageIndex==1){
                            lifesearch_result_llerror.visibility=View.VISIBLE
                            lifesearch_result_rv.visibility=View.GONE
                        }else{
                            lifesearch_result_llerror.visibility=View.GONE
                            lifesearch_result_rv.visibility=View.VISIBLE
                        }
                        if (e is OtherException){
                            showToastMsg(e.msg)

                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }
                })
    }

    override fun onDestroy() {
        super.onDestroy()
        AppUtils.destroyImmersionBar(this)
    }
}